import type { Fn } from '../types/common';

export class WindowHelper {
  static resizeCache = {};
  static addOnResize(key: string, cb: Fn) {
    WindowHelper.resizeCache[key] = cb;
    WindowHelper.buildResize();
  }

  static removeOnResize(key: string) {
    WindowHelper.resizeCache[key] = undefined;
    WindowHelper.buildResize();
  }

  private static buildResize() {
    window.onresize = function () {
      for (const k in WindowHelper.resizeCache) {
        if (typeof WindowHelper.resizeCache[k] === 'function') {
          WindowHelper.resizeCache[k]();
        }
      }
    };
  }

  static scrollCache = {};
  static addOnScroll(key: string, cb: Fn) {
    WindowHelper.scrollCache[key] = cb;
    WindowHelper.buildScroll();
  }

  static removeOnScroll(key: string) {
    if (key in WindowHelper.scrollCache) {
      delete WindowHelper.scrollCache[key];
    }
    WindowHelper.buildScroll();
  }

  private static buildScroll() {
    window.onscroll = function () {
      for (const k in WindowHelper.scrollCache) {
        if (typeof WindowHelper.scrollCache[k] === 'function') {
          WindowHelper.scrollCache[k]();
        }
      }
    };
  }
}
